﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using System.Drawing;
using System.Text.RegularExpressions;
using System.IO.Compression;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace RukouMVC.Helpers
{
    public class OtherHelpers
    {
        //加密解密字符串
        public static string EncryptData(String strKey, String strData)
        {
            string strValue;
            strValue = "";


            if (strKey.Length > 0)
            {
                if (strKey.Length < 16)
                {
                    strKey = strKey + "XXXXXXXXXXXXXXXX".Substring(0, 16 - strKey.Length);

                }
                if (strKey.Length > 16)
                {
                    strKey = strKey.Substring(0, 16);
                }


                // create encryption keys
                Byte[] byteKey = Encoding.UTF8.GetBytes(strKey.Substring(0, 8));
                Byte[] byteVector = Encoding.UTF8.GetBytes(strKey.Substring(strKey.Length - 9, 8));


                // convert data to byte array
                Byte[] byteData = Encoding.UTF8.GetBytes(strData);

                // encrypt 
                DESCryptoServiceProvider objDES = new DESCryptoServiceProvider();
                MemoryStream objMemoryStream = new MemoryStream();
                CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateEncryptor(byteKey, byteVector), CryptoStreamMode.Write);
                objCryptoStream.Write(byteData, 0, byteData.Length);
                objCryptoStream.FlushFinalBlock();





                //convert to string and Base64 encode
                strValue = Convert.ToBase64String(objMemoryStream.ToArray());

                // do something 
            }
            else
            {
                strValue = strData;
            }

            return strValue;
        }

        public static string DecryptData(String strKey, String strData)
        {
            if (strData == null)
            {
                return "";
            }
            string strValue = "";
            if (strKey.Length > 0)
            {
                if (strKey.Length < 16)
                {
                    strKey = strKey + "XXXXXXXXXXXXXXXX".Substring(0, 16 - strKey.Length);
                }

                if (strKey.Length > 16)
                {
                    strKey = strKey.Substring(0, 16);
                }
                // create encryption keys
                Byte[] byteKey = Encoding.UTF8.GetBytes(strKey.Substring(0, 8));
                Byte[] byteVector = Encoding.UTF8.GetBytes(strKey.Substring(strKey.Length - 9, 8));

                // convert data to byte array and Base64 decode
                Byte[] byteData = new Byte[strData.Length];
                try
                {
                    byteData = Convert.FromBase64String(strData);

                }

                catch
                {
                    strValue = strData;
                }

                if (strValue.Length == 0)
                {
                    try
                    {
                        // decrypt
                        DESCryptoServiceProvider objDES = new DESCryptoServiceProvider();
                        MemoryStream objMemoryStream = new MemoryStream();
                        CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write);
                        objCryptoStream.Write(byteData, 0, byteData.Length);
                        objCryptoStream.FlushFinalBlock();


                        // convert to string
                        Encoding objEncoding = Encoding.UTF8;


                        strValue = objEncoding.GetString(objMemoryStream.ToArray());


                    }
                    catch
                    {
                        strValue = "";
                    }

                }

            }
            else
            {
                strValue = strData;


            }

            return strValue;
        }


        //获取别的网站的资源
        public static bool GetIcon(string url)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = 20000;
                request.AllowAutoRedirect = false;
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return true;
                }
            }
            catch
            {
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (request != null)
                    request = null;
            }
            return false;
        }

        public static string GetEncoding(string url)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = 20000;
                request.AllowAutoRedirect = false;
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
                {
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress));
                    else
                        reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
                    string html = reader.ReadToEnd();
                    Regex reg_charset = new Regex(@"charset\b\s*=\s*(?<charset>[^""]*)");
                    if (reg_charset.IsMatch(html))
                    {
                        return reg_charset.Match(html).Groups["charset"].Value;
                    }
                    else if (response.CharacterSet != string.Empty)
                    {
                        return response.CharacterSet;
                    }
                    else
                        return Encoding.Default.BodyName;
                }
            }
            catch
            {
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (reader != null)
                    reader.Close();
                if (request != null)
                    request = null;
            }
            return Encoding.Default.BodyName;
        }

        public static string GetHtml(string url, Encoding encoding)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = 20000;
                request.AllowAutoRedirect = false;
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
                {
                    if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding);
                    else
                        reader = new StreamReader(response.GetResponseStream(), encoding);
                    string html = reader.ReadToEnd();
                    return html;
                }
            }
            catch
            {
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (reader != null)
                    reader.Close();
                if (request != null)
                    request = null;
            }
            return string.Empty;
        }


        //上传网站图标
        public static string[] UpLoadIconFile(string fileNamePath)
        {
            FileInfo file = new FileInfo(fileNamePath);


            string fileName = GetFileName() + file.Extension;
            string fileName_icon = "/ico/icon/" + fileName + "_icon.jpg";
            string fileName_thumb = "/ico/thumb/" + fileName + "_thumb.jpg";
            string fileName_small = "/ico/small/" + fileName + "_small.jpg";
            string fileName_large = "/ico/large/" + fileName + "_large.jpg";

            string originalfile = UpLoadFile(fileNamePath, "/ico/original/", fileName + file.Extension);
            MakeThumbnail(fileNamePath, HttpContext.Current.Server.MapPath(fileName_icon), 16, 16, "Cut");
            MakeThumbnail(fileNamePath, HttpContext.Current.Server.MapPath(fileName_thumb), 51, 51, "Cut");
            MakeThumbnail(fileNamePath, HttpContext.Current.Server.MapPath(fileName_small), 140, 70, "Cut");
            MakeThumbnail(fileNamePath, HttpContext.Current.Server.MapPath(fileName_large), 160, 160, "Cut");
            string[] iconUrls = new string[] { "/ico/original/" + file.Name, fileName_icon,
            fileName_thumb, fileName_small,fileName_large};

            return iconUrls;
        }

        //上传用户头像
        public static string[] UpLoadUserIconFile(HttpPostedFileBase file, string fileNamePath)
        {
            //FileInfo file = new FileInfo(fileNamePath);

            string fileName = GetFileName() + file.FileName.Substring(file.FileName.LastIndexOf('.'));
            string fileName_icon = "/upload/usericon/" + fileName + "_icon.jpg";
            string fileName_thumb = "/upload/usericon/" + fileName + "_thumb.jpg";
            string fileName_small = "/upload/usericon/" + fileName + "_small.jpg";
            string fileName_large = "/upload/usericon/" + fileName + "_large.jpg";

            //string originalfile = UpLoadFile(fileNamePath, "/upload/usericon/", fileName );
            file.SaveAs(HttpContext.Current.Server.MapPath("/upload/usericon/") + fileName);
            //MakeThumbnail(file.FileName,HttpContext.Current.Server.MapPath(fileName_icon), 48, 48, "Cut");
            //MakeThumbnail(file.FileName, HttpContext.Current.Server.MapPath(fileName_thumb), 98, 98, "Cut");
            //MakeThumbnail(file.FileName, HttpContext.Current.Server.MapPath(fileName_small), 200, 150, "Cut");
            //MakeThumbnail(file.FileName, HttpContext.Current.Server.MapPath(fileName_large), 300, 300, "Cut");


            MakeThumbnail_Stream(file, HttpContext.Current.Server.MapPath(fileName_icon), 48, 48, "Cut");
            MakeThumbnail_Stream(file, HttpContext.Current.Server.MapPath(fileName_thumb), 98, 98, "Cut");
            MakeThumbnail_Stream(file, HttpContext.Current.Server.MapPath(fileName_small), 200, 150, "Cut");
            MakeThumbnail_Stream(file, HttpContext.Current.Server.MapPath(fileName_large), 300, 300, "Cut");
            string[] iconUrls = new string[] { "/upload/usericon/" + fileName, fileName_icon,
            fileName_thumb, fileName_small,fileName_large};

            return iconUrls;
        }

        private static string UpLoadFile(string fileNamePath, string toFilePath, string fileName)
        {
            try
            {
                FileInfo file = new FileInfo(fileNamePath);

                string fileNameExt = file.Extension;

                if (CheckFileExt(fileNameExt))
                {
                    if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";

                    string serverFileName = toFilePath + fileName;

                    string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);

                    if (!Directory.Exists(toFileFullPath))
                    {
                        Directory.CreateDirectory(toFileFullPath);
                    }
                    string toFile = toFileFullPath + fileName;

                    WebClient myWebClient = new WebClient();

                    myWebClient.Credentials = CredentialCache.DefaultCredentials;

                    FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);

                    BinaryReader r = new BinaryReader(fs);

                    byte[] postArray = r.ReadBytes((int)fs.Length);
                    Stream postStream = myWebClient.OpenWrite(toFile, "PUT");
                    if (postStream.CanWrite)
                    {
                        postStream.Write(postArray, 0, postArray.Length);
                    }
                    else
                    {
                        return "0|" + serverFileName + "|" + "文件目前不可写";
                    }
                    postStream.Close();


                    return "1|" + serverFileName + "|" + "文件上传成功";
                }
                else
                {
                    return "0|errorfile|" + "文件格式非法";
                }
            }
            catch (Exception e)
            {
                return "0|errorfile|" + "文件上传失败,错误原因：" + e.Message;
            }
        }

        private static bool CheckFileExt(string _fileExt)
        {
            string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".bmp", ".ico" };
            for (int i = 0; i < allowExt.Length; i++)
            {
                if (allowExt[i] == _fileExt) { return true; }
            }
            return false;

        }

        private static string GetFileName()
        {
            Random rd = new Random();
            StringBuilder serial = new StringBuilder();
            serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
            serial.Append(rd.Next(0, 999999).ToString());
            return serial.ToString();

        }


        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            

            WebClient myWebClient = new WebClient();

            myWebClient.Credentials = CredentialCache.DefaultCredentials;

            FileStream fs = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read);

            BinaryReader r = new BinaryReader(fs);

            byte[] postArray = r.ReadBytes((int)fs.Length);
           // Stream postStream = myWebClient.OpenWrite(toFile, "PUT");

            Image originalImage = Image.FromStream(r.BaseStream);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                                 
                    break;
                case "W"://指定宽，高按比例                                         
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例 
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                                 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片 
            Image bitmap = new Bitmap(towidth, toheight);

            //新建一个画板 
            Graphics g = Graphics.FromImage(bitmap);

            //设置高质量插值法 
            g.InterpolationMode = InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度 
            g.SmoothingMode = SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充 
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分 
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                    new Rectangle(x, y, ow, oh),
                    GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图 
                bitmap.Save(thumbnailPath, ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        public static void MakeThumbnail_Stream(HttpPostedFileBase file,  string thumbnailPath, int width, int height, string mode)
        {
            Image originalImage = Image.FromStream(file.InputStream);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                                 
                    break;
                case "W"://指定宽，高按比例                                         
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例 
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                                 
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            //新建一个bmp图片 
            Image bitmap = new Bitmap(towidth, toheight);

            //新建一个画板 
            Graphics g = Graphics.FromImage(bitmap);

            //设置高质量插值法 
            g.InterpolationMode = InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度 
            g.SmoothingMode = SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充 
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分 
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                    new Rectangle(x, y, ow, oh),
                    GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图 
                bitmap.Save(thumbnailPath, ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// 在图片上增加文字水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_sy">生成的带文字水印的图片路径</param>
        public static void AddWater(string Path, string Path_sy)
        {
            string addText = "93cm.com";
            Image image = Image.FromFile(Path);
            Graphics g = Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            Font f = new Font("Verdana ", 60);
            Brush b = new SolidBrush(Color.Green);

            g.DrawString(addText, f, b, 35, 35);
            g.Dispose();

            image.Save(Path_sy);
            image.Dispose();


        }

        ///   <summary> 
        ///   在图片上生成图片水印 
        ///   </summary> 
        ///   <param   name= "Path "> 原服务器图片路径 </param> 
        ///   <param   name= "Path_syp "> 生成的带图片水印的图片路径 </param> 
        ///   <param   name= "Path_sypf "> 水印图片路径 </param> 
        public static void AddWaterPic(string Path, string Path_syp, string Path_sypf)
        {
            Image image = Image.FromFile(Path);
            Image copyImage = Image.FromFile(Path_sypf);
            Graphics g = Graphics.FromImage(image);
            g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
            g.Dispose();

            image.Save(Path_syp);
            image.Dispose();
        }
    }
}
